package com.dailywork.basepro.thread.executors;

import java.util.concurrent.*;

/**
 * 自定义线程池(使用有界队列)
 *
 * @author think
 * @version 1.0.0
 * @since 2020/4/25
 */
public class UseThreadPoolExecutor1 {

    /**
     * 在使用有界队列时,若有新的任务需要执行,如果线程池实际线程数小于corePoolSize,则优先创建线程, 若大于corePoolSize,则会将任务加入队列,
     * 若队列已满,则在总线程数不大于MaxNumPoolSize的前提下,创建新的线程, 若线程数大于MaxNumPoolSize,则执行拒绝策略,或其他自定义方式
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor pool =
                new ThreadPoolExecutor(
                        1,
                        2,
                        60,
                        TimeUnit.SECONDS,
                        new ArrayBlockingQueue<>(3),
                        new MyRejected()
                );

        MyTask mt1 = new MyTask(1, "任务1");
        MyTask mt2 = new MyTask(2, "任务2");
        MyTask mt3 = new MyTask(3, "任务3");
        MyTask mt4 = new MyTask(4, "任务4");
        MyTask mt5 = new MyTask(5, "任务5");
        MyTask mt6 = new MyTask(6, "任务6");

        MyCallTask myCallTask = new MyCallTask();

        pool.execute(mt1);
        pool.execute(mt2);
        pool.execute(mt3);
        pool.execute(mt4);
        pool.execute(mt5);
        pool.execute(mt6);
        Future<String> result = pool.submit(myCallTask);
        System.out.println(result.get());

        pool.shutdown();
    }
}
